package gateway.outbound.netty4;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import gateway.router.HttpEndpointRouter;
import gateway.router.RandomHttpEndpointRouter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.handler.codec.http.HttpRequest;

import java.util.List;

public class NettyHttpClientOutboundHandler extends ChannelInboundHandlerAdapter {

    private final List<String> backendUrls;

    HttpEndpointRouter router = new RandomHttpEndpointRouter();
    NettyHttpClient client = new NettyHttpClient();

    private HttpRequest request;

    public NettyHttpClientOutboundHandler(List<String> backendUrls) {
        this.backendUrls = backendUrls;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        String backendUrl = router.route(this.backendUrls);

        client.connect(backendUrl);
//        if (msg instanceof HttpRequest) {
//            request = (HttpRequest) msg;
//
//            String uri = request.getUri();
//            System.out.println("Uri:" + uri);
//        }
//        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;
            ByteBuf buf = content.content();
            System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));
            buf.release();

            String res = "I am OK";
            FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
                    OK, Unpooled.wrappedBuffer(res.getBytes("UTF-8")));
            response.headers().set(CONTENT_TYPE, "text/plain");
            response.headers().set(CONTENT_LENGTH,
                    response.content().readableBytes());
//            if (HttpHeaders.isKeepAlive(request)) {
//                response.headers().set(CONNECTION, Values.KEEP_ALIVE);
//            }
            ctx.write(response);
            ctx.flush();
//        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
}